{% extends "endbase.html" %}
{% block title %}
	发布博客
{% endblock %}

{% block head %}
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
	<link rel="stylesheet" href="{{ url_for('static',filename='css/editormd.min.css') }}" />
    <script src="{{ url_for('static',filename='js/jquery.min.js') }}"></script>
    <script src="{{ url_for('static',filename='js/editormd.min.js') }}"></script>

    <style>
        @font-face {
            font-family: 'editormd';
            src: url("{{ url_for('static', filename='fonts/editormd.woff') }}") format('woff');
            font-weight: normal;
            font-style: normal;
        }

    </style>
{% endblock %}

{% block body %}
    <div class="container" style="height: 100vh; ">
        <i class="fas fa-arrow-left" style="font-size: 24px; margin-right: 10px; margin-top: 10px"></i>
        <form action="{{ url_for('security.write_blog') }}" method="post" enctype="multipart/form-data">
            <div class="row">
                <div class="col-md-9">
                    <div class="title-input" style="margin-bottom: 30px;margin-top: 10px;">
                        <input type="text"
                               name="title"
                               class="underline-input"
                               placeholder="点击输入博客标题"
                               value="{{ blog.title if blog else '' }}"
                               style="font-size: 20px; width: 100%; border: none; border-bottom: 2px solid #333; padding: 10px 0; outline: none;text-decoration: none">
                        <input type="hidden" name="author_id" value="{{ blog.author_id if blog else user.id }}">
                        {% if blog %}
                            <input type="hidden" name="blog_id" value="{{ blog.id }}">
                        {% endif %}

                    </div>
                </div>
               <div class="col-md-3 form-group">
                    <label>上传封面图：</label>
                    {% if blog and blog.picture %}
                        <div style="margin-bottom: 10px;">
                            <img src="{{ url_for('static', filename=blog.picture) }}" alt="原始封面" style="width: 100px; max-height: 100px; object-fit: contain; border: 1px solid #ccc;"/>
                            <p style="font-size: 13px; color: gray;">当前封面</p>
                        </div>
                    {% endif %}
                    <input type="file" name="picture" class="form-control" style="outline: none; text-decoration: none; height: 40px;">
                </div>

            </div>
            <div id="editor">
            <!-- Tips: Editor.md can auto append a `<textarea>` tag -->
            <textarea style="display:none;" name="content">{{ blog.content if blog else '### Hello Editor.md !' }}</textarea>
            </div>

            <div class="row form-horizontal" style="margin: 10px 0 30px -15px ;">
                <div class="form-group col-md-4 categorieblog ">
                    <div class="col-md-12">
                        <select class=" form-control" name="categorie_id">
                             <option>选择分类</option>
                            {% for category in categories %}
                            	<option value="{{ category.id }} " {% if blog and blog.categorie_id==category.id %} selected {% endif %}>
                                    {{ category.name }}
                                </option>
                            {% endfor %}
                        </select>
                    </div>

                </div>
                <div class="form-group bannerblog col-md-4">
                    <div class="col-md-12">
                        <input type="text" name="tags" class="form-control" placeholder="添加标签 (空格分隔)"
                                value="{% if blog %}{{ blog.tags | map(attribute='name') | join(' ') }}{% endif %}">
                    </div>
                </div>
                <div class="form-group col-md-4">
                    <div class=" col-md-6">
                        <button class="btn btn-warning btn-lg" style="outline: none;text-decoration: none" type="submit" name="status" value="draft" >
                             保存为草稿
                        </button>
                    </div>
                    <div class=" col-md-6 text-right pull-rights" >
                        <button class="btn btn-success btn-lg" style="outline: none;text-decoration: none" type="submit" name="status" value="published" >
                            <i class="glyphicon glyphicon-pencil"></i> 立即发布
                        </button>
                    </div>
                </div>
            </div>
        </form>
        <script type="text/javascript">
            $(function() {
                var editor = editormd("editor", {
                     width: "100%",
                     height:  "calc(100vh - 200px)",
                     //markdown: "xxxx",     // dynamic set Markdown text
                    path : "{{ url_for('static',filename='/lib/') }}",
                    toolbarIcons : [  <!-- 精简工具栏 -->
                        "undo","redo","hr","table","datetime","emoji","|",
                        "bold", "italic", "quote", "|",
                        "list-ul", "list-ol", "|",
                        "link", "image", "code", "|",
                        "preview", "fullscreen","help"
                    ],
                    emoji: true,
                    emojiPath: "{{ url_for('static', filename='plugins/emoji-dialog/emoji/') }}",
                    imageUpload : true,  <!-- 启用图片上传 -->
                    imageFormats : ["jpg", "png", "gif"],
                    imageUploadURL : "{{ url_for('security.upload_image') }}" //需在后端实现该路由
                });
                // ✅ 粘贴图片支持
                $("#editor").on("paste", function (e) {
                    var clipboardData = e.originalEvent.clipboardData;
                    if (!clipboardData) return;

                    var items = clipboardData.items;
                    if (!items) return;

                    for (var i = 0; i < items.length; i++) {
                        if (items[i].type.indexOf("image") !== -1) {
                            var file = items[i].getAsFile();
                            uploadImage(file);
                        }
                    }
                });

                // ✅ 拖拽上传支持
                $("#editor").on("drop", function (e) {
                    e.preventDefault();
                    var files = e.originalEvent.dataTransfer.files;
                    if (files.length > 0) {
                        for (var i = 0; i < files.length; i++) {
                            uploadImage(files[i]);
                        }
                    }
                });

                function uploadImage(file) {
                    var formData = new FormData();
                    formData.append("editormd-image-file", file);

                    $.ajax({
                        url: "{{ url_for('security.upload_image') }}",
                        type: "POST",
                        data: formData,
                        cache: false,
                        contentType: false,
                        processData: false,
                        success: function (res) {
                            if (res.success === 1) {
                                editor.insertValue("![](" + res.url + ")");
                            } else {
                                alert("上传失败：" + res.message);
                            }
                        },
                        error: function () {
                            alert("上传请求失败！");
                        }
                    });
                }
            });
        </script>

    </div>
    {% with messages=get_flashed_messages(with_categories=true) %}
        {% if messages %}
            <script>
                {% for category,message in messages %}
                    alert("{{ message }}");
                {% endfor %}
            </script>
        {% endif %}
    {% endwith %}
{% endblock %}